import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap, customRouterMap } from './router.config.js'
import store from '../store'
import { decryptByAES } from '../util/crypto.js'
import { GetRoleMenu, getConfig, GetMenu } from '@/api'
import {
  SelectList as SelectListApp
} from '@/api/admin/app'
// hack router replace callback
const originalReplace = Router.prototype.replace
Router.prototype.replace = function replace(location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}
const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

const createRouter = () =>
  new Router({
    mode: 'history', // 如果你是 history模式 需要配置vue.config.js publicPath
    base: `/${process.env.VUE_APP_ENV || ''}`,
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRouterMap
  })

const router = createRouter()
router.beforeEach(async (to, from, next) => { //beforeEach是router的钩子函数，在进入路由前执行
  if (to.meta.title) { //判断是否有标题
    document.title = to.meta.title
  }
  // 刷新配置
  if (to.path.split('/').length >= from.path.split('/').length) {
    store.commit('setRefresh', true)
  } else {
    store.commit('setRefresh', false)
  }
  if (from.meta.keepAlive) {
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    from.meta.scrollTop = scrollTop;
  }
  if (to.meta.anonymous) {
    // 游客模式
     console.log('xxxxx---', store.getters.token, '---', sessionStorage.getItem('token') , to.path, from.path)
     if (to.path == '/auto' || store.getters.token) {
      console.log('xxxxx---', '00')
      next()
      return
     }
    if (!sessionStorage.getItem('token')) {
      console.log('xxxxx---', '11')
      next()
      return
    }
  
  }

  if (store.getters.token) {
    // 存在用户继续
    next()
    return
  }
  try {
    // 获取locationStore
    let { userid, token, username, orgCode, personName, role, version } = JSON.parse(decryptByAES(localStorage.getItem('config-user')) || '{}')
    console.log('xxxxx', token, username, personName, role, orgCode);
    if (token) {
      getConfig({
        codes: ['sysName', 'unit', 'address', 'footerMsg', 'icp'].join(',')
      }).then((res) => {
        console.log('getConfig', res)
        if (res.code === 20000) {
          let form = {}
          res.data.forEach(d => {
            form[d.code] = d.value
          })
          store.commit('setAppConfig', form)
        }
      })
      // 重置路由
      router.matcher = createRouter().matcher
      // 获取 app
      let apps = await SelectListApp().then(res => {
        return res.data
      })
      let ids = []
      // 菜单id
      let menuIds = await loadUserRoleMenu(role, apps, ids)
      console.log('menuIds', menuIds)
      // 加载路由菜单
      let menu = loadMenu(customRouterMap, menuIds)
      console.log('menu', menu)
      if (menu) {
        router.addRoutes(menu)
      }
      let menus = await GetMenu().then(res => res.data).catch(() => [])
      console.log('menu2', menus)
      // 存在用户
      store.dispatch('setUserName', personName)
      store.commit('setUsername', username)
      store.commit('setToken', token)
      // 子菜单处理调整
      // 盘点是否是动态菜单，有动态菜单，
      let mm2 = menus.filter(d => ids.some(j => j.indexOf(d.menuUri) == 0))
      console.log('mm2', mm2)
      store.commit('setMenus', mm2)
      store.commit('setRole', role)
      store.commit('setOrgCode', orgCode)
      store.commit('setVersion', version)
      sessionStorage.setItem('token', token)
      sessionStorage.setItem('userid', userid)
      if (to.path != '/login') {
        next({ ...to, replace: true })
      } else {
        next({ path: '/', replace: true })
      }
      return
    }
    console.log('xxxxx', to);
    // 去登录
    sessionStorage.setItem('history-page', to.path)
    next({ path: '/login' })
  } catch (e) {
    console.error(e)
    sessionStorage.removeItem('token')
    localStorage.removeItem('config-user')
    next({ path: '/login' })
  }
})

// 加载用户角色信息
export const loadUserRoleMenu = (roleId, apps, ids) => {
 let appMap = apps.reduce((a, b) => {
    a[b.id] = b
    return a
  }, {})
  return GetRoleMenu({roleId}).then(res => {
    console.log('GetRoleMenu====>', res);
    if (res && res.code === 20000) {
      return res.data.map(d => {
        ids.push(d.menu)
        // 特殊处理
        if (d.menu.includes('_index') && d.menu == `${d.appId}_index`) {
          // 动态应用
          if (appMap[d.appId]) {
            store.commit('addDynamicsPage', appMap[d.appId])
            return appMap[d.appId].appUrl
          }
        }
        return d.menu
      })
    }
    return []
  })
}
// 加载自定义菜单
function loadMenu(routerData, menuIds) {
  let result = routerData.slice(0).filter(d => {
    if (d.meta && d.meta.anonymous || d.redirect) {
      return true
    }
    return d.children || (menuIds && menuIds.includes(d.path))
  }).map(d => {
    d = Object.assign({}, d)
    if (d.children) {
      let data = loadMenu(d.children, menuIds)
      if (data) {
        d.children = data
      }
    }
  
    return d
  })
  // 修改重定向地址
  if (result && result.length > 0 && menuIds) {
    result.forEach(d => {
      if (!menuIds.includes(d.redirect) && d.children && d.children.length > 0) {
        d.redirect = d.children[0].path
      }
    })
  }
  // if (result && result.length > 0 && menuIds //
  //   && !menuIds.includes(result[0].redirect) //
  //   && result[0].children && result[0].children.length > 0) {
  //   result[0].redirect = result[0].children[0].path
  // }
  console.log('ssss', result)
  return result
}

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
